use crate::demo::d_enum::*;
use crate::demo::d_enum::IPKind;

#[cfg(test)]
pub mod test_match {
    use super::dmatch;

    #[test]
    fn tmatch() {
        dmatch();
    }
}
pub fn dmatch() {
    /* 强大的控制流运算 match
        - 允许一个值与一系列模式进行匹配， 并执行匹配的代码
        - 模式可以是字面值 变量名 通配符
        - 必须穷举所有
        - “_”: 替代剩余没有列出的值 

        绑定值的模式
        - 可以从enum变体中提取值
     */
    println!(" --------- match ------------- ");
    let m = Message::Color(255, 0, 0, 1);
    let mm = match_message(m);
    let ip = Message::IP(IPKind::V4);
    let ipk = match_message(ip);
    println!("mm = {}", mm);
    println!("ipl = {}", ipk);

    let a = 15u8;
    match a {
        1 => println!("a = 1"),
        3 => println!("a = 3"),
        5 => println!("a = 5"),
        7 => println!("a = 7"),
        _ => println!("a = other"),
    }

    let o1 = Some(6);
    let o2 = option_add(o1);
    println!("o1 = {:?}", o2);

}

fn match_message(m: Message) -> u8 {
    match m {
        Message::Quit => 0,
        Message::Move { x, y } => {
            println!("Move: x={} y={}", x, y);
            1
        }
        Message::Write(s) => {
            println!("Write: {}", s);
            2
        },
        Message::Color(r, g, b, a) =>  {
            println!("color: ({}, {}, {}, {})", r, g, b, a);
            3
        },
        Message::IP(ip) => {
            println!("IP: {:?}", ip);
            4
        }
    }
}

fn option_add(o: Option<u8>) -> Option<u8> {
    match o {
        None => None,
        Some(n) => Some(n+1),
    }
}